package org.utils.io;

import java.io.File;
import java.io.FileFilter;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 * @author Manuel EVENO
 */
public class FileRenamer
{
	private Logger logger = null;
	/**
	 * Constructor for FileRenamer.
	 */
	public FileRenamer()
	{
		super();
		logger = Logger.getLogger(getClass());
	}
	/**
	 * Rename all the files with the specified extension located in the specified
	 * directory with the new extension specified
	 * @param dir the dir to scan
	 * @param extension the extension to look for
	 * @param newExtension the new extension to replace
	 */
	public void rename(String dir, String extension, String newExtension, boolean recurse)
	{
		File directory = new File(dir);
		if (! directory.isDirectory())
			throw new IllegalArgumentException("The specified dir is not a directory: "+directory);
		rename(directory, extension, newExtension, recurse);
	}
	/**
	 * Rename all the files with the specified extension located in the specified
	 * directory with the new extension specified
	 * @param dir the dir to scan
	 * @param extension the extension to look for
	 * @param newExtension the new extension to replace
	 */
	public void rename(File dir, String extension, String newExtension, boolean recurse)
	{
		GenericFileFilter filter = new GenericFileFilter();
		filter.addFileType(extension);
		filter.setAcceptDirectories(false);
//		if (recurse)
		File[] files = dir.listFiles((FileFilter)filter);
		for (int i = 0; i < files.length; i++)
		{
			File newFile = new File( FileUtils.getFileBaseName(files[i])+'.'+newExtension );
			if (! files[i].renameTo(newFile))
				logger.warn("Can't rename file \""+files[i].getName()+"\" to \""+newFile.getName()+"\"");
		}
	}

	public static void main(String[] args)
	{
		BasicConfigurator.configure();
		if (args.length == 2)
			new FileRenamer().rename(".", args[0], args[1], false);
		else if (args.length == 3)
			new FileRenamer().rename(args[0], args[1], args[2], false);
		else
		{
			Logger.getLogger(Thread.currentThread().getClass()).error("Wrong number of argument");
			System.err.println("Usage is:");
			System.err.println("\tFileRenamer [path] extension new-extension");
		}
	}	
}
